package com.cimu.umeng;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class HttpLogInterceptor implements Interceptor {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public static String TAG = "LogInterceptor";
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        String method = request.method();
        StringBuilder sb = new StringBuilder();

        if ("POST".equals(method)) {
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
            }
        }
        logger.info("[start---({}, {}, {})]", request.toString(), method, sb.toString());
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        logger.info("[end---({}, {}, {}, {}ms)]", request.toString(), method, sb.toString(), duration);
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }
}